Page({
  data: {
    chessBoard: Array(15).fill().map(() => Array(15).fill(0)),
    currentPlayer: 1,
    gameOver: false,
    statusText: "黑方回合",
    AIPlayer: true,
    processing: false
  },

  onLoad() {
    this.initBoard();
  },

  initBoard() {
    this.setData({
      chessBoard: Array(15).fill().map(() => Array(15).fill(0)),
      currentPlayer: 1,
      gameOver: false,
      statusText: "黑方回合",
      processing: false
    });
  },

  handleTap(e) {
    if (this.data.gameOver || this.data.processing) return;
    
    const {x, y} = e.currentTarget.dataset;
    const board = this.data.chessBoard;
    
    if (board[x][y] !== 0) return;

    this.setData({ processing: true });
    
    // 玩家落子
    board[x][y] = 1;
    this.setData({ chessBoard: board }, () => {
      if (this.checkWin(x, y)) {
        this.showResult();
      } else if (this.isBoardFull()) {
        this.showDraw();
      } else {
        this.setData({ 
          statusText: "AI思考中...",
          processing: true
        }, () => {
          setTimeout(() => this.AITurn(), 200); // 优化响应速度
        });
      }
    });
  },

  AITurn() {
    const bestPos = this.calculateBestMove();
    const board = this.data.chessBoard;
    
    if (board[bestPos.x][bestPos.y] === 0) {
      board[bestPos.x][bestPos.y] = 2;
      this.setData({ 
        chessBoard: board,
        processing: false 
      }, () => {
        if (this.checkWin(bestPos.x, bestPos.y)) {
          this.showResult();
        } else if (this.isBoardFull()) {
          this.showDraw();
        } else {
          this.setData({
            currentPlayer: 1,
            statusText: "黑方回合"
          });
        }
      });
    }
  },

  // 优化后胜负判断
  checkWin(x, y) {
    const directions = [
      [[-1,0], [1,0]],  // 水平
      [[0,-1], [0,1]],  // 垂直
      [[-1,-1], [1,1]], // 主对角线
      [[-1,1], [1,-1]]  // 副对角线
    ];
  
    const currentColor = this.data.chessBoard[x][y];
    
    for (let dir of directions) {
      let count = 1;
      
      // 正方向扫描
      let [dx, dy] = dir[0];
      let i = x + dx, j = y + dy;
      while (i >= 0 && i < 15 && j >= 0 && j < 15) {
        if (this.data.chessBoard[i][j] === currentColor) {
          count++;
          i += dx;
          j += dy;
        } else {
          break;
        }
      }
  
      // 反方向扫描
      [dx, dy] = dir[1];
      i = x + dx, j = y + dy;
      while (i >= 0 && i < 15 && j >= 0 && j < 15) {
        if (this.data.chessBoard[i][j] === currentColor) {
          count++;
          i += dx;
          j += dy;
        } else {
          break;
        }
      }
  
      if (count >= 5) {
        this.setData({ gameOver: true });
        return true;
      }
    }
    return false;
  },

  // 增强版AI决策
  calculateBestMove() {
    const weightMap = this.getEnhancedWeightMap();
    let maxScore = -Infinity;
    let candidates = [];
    
    for(let i = 0; i < 15; i++) {
      for(let j = 0; j < 15; j++) {
        if(this.data.chessBoard[i][j] !== 0) continue;
        
        let score = this.calculatePositionScore(i, j, weightMap);
        if(score > maxScore) {
          maxScore = score;
          candidates = [{x:i, y:j}];
        } else if(score === maxScore) {
          candidates.push({x:i, y:j});
        }
      }
    }
    return candidates.length > 0 ? 
      candidates[Math.floor(Math.random() * candidates.length)] : 
      {x:7, y:7};
  },

  calculatePositionScore(x, y, weightMap) {
    let totalScore = 0;
    const scanDirections = [
      [1,0], [-1,0], [0,1], [0,-1],
      [1,1], [-1,-1], [1,-1], [-1,1]
    ];
    
    scanDirections.forEach(([dx, dy]) => {
      const pattern = this.getDirectionPattern(x, y, dx, dy);
      totalScore += weightMap[pattern] || 0;
    });
    
    // 中心区域加成
    const distanceFromCenter = Math.abs(x-7) + Math.abs(y-7);
    totalScore += (14 - distanceFromCenter) * 10;
    
    return totalScore;
  },

  getDirectionPattern(x, y, dx, dy) {
    let pattern = '';
    // 正方向扫描（0-4格）
    for(let i=1; i<=4; i++) {
      const tx = x + dx*i;
      const ty = y + dy*i;
      if(tx <0 || tx >=15 || ty <0 || ty >=15) break;
      pattern += this.data.chessBoard[tx][ty] || 0;
    }
    // 反方向扫描（0-4格）
    for(let i=1; i<=4; i++) {
      const tx = x - dx*i;
      const ty = y - dy*i;
      if(tx <0 || tx >=15 || ty <0 || ty >=15) break;
      pattern = (this.data.chessBoard[tx][ty] || 0) + pattern;
    }
    // 转换视角：AI=2，玩家=1 → 转换为AI视角的1
    return pattern.replace(/2/g,'1').replace(/1/g,'2');
  },

  getEnhancedWeightMap() {
    return {
      // AI进攻模式
      '11110': 100000,  // 活四
      '11101': 90000,   // 跳活四
      '11011': 90000,
      '011110': 150000, // 连活四
      '1111': 30000,    // 死四
      '1110': 25000,    // 活三
      '1101': 20000,    // 跳活三
      '1011': 20000,
      '01110': 30000,   // 连活三
      
      // 玩家防御模式
      '22220': 95000,   // 拦截活四
      '22202': 85000,   // 拦截跳活四
      '22022': 85000,
      '022220': 140000, // 拦截连活四 
      '2222': 35000,    // 拦截死四
      '2220': 30000,    // 拦截活三
      '2202': 25000,    // 拦截跳活三
      '2022': 25000,
      '02220': 35000,   // 拦截连活三
      
      // 基础棋型
      '2200': 1000,
      '2002': 800,
      '1100': 500,
      '0011': 500,
    };
  },

  // 其他辅助方法保持不变
  toggleAIMode() {
    this.setData({ 
      AIPlayer: !this.data.AIPlayer,
      statusText: !this.data.AIPlayer ? "AI已启用" : "玩家对战"
    });
    this.initBoard();
  },

  isBoardFull() {
    return this.data.chessBoard.every(row => row.every(cell => cell !== 0));
  },

  showResult() {
    const winner = this.data.currentPlayer === 1 ? '黑方胜利！' : '白方胜利！';
    this.setData({ 
      gameOver: true,
      statusText: winner
    });
    wx.showToast({ title: winner, icon: 'none' });
  },

  showDraw() {
    this.setData({ 
      gameOver: true,
      statusText: "平局！"
    });
    wx.showToast({ title: '棋盘已满，平局！', icon: 'none' });
  },

  restartGame() {
    this.initBoard();
    wx.showToast({ title: '新游戏开始', icon: 'success' });
  }
});